﻿using System;
using JetBrains.Annotations;
using JetBrains.ReSharper.Psi;

namespace MugenMvvmToolkit.ReSharper.PluginModels
{
    public struct ViewMetaModel
    {
        #region Constructors

        public ViewMetaModel([NotNull] IInterface @interface, [NotNull] IAttributeInstance attribute,
            [NotNull] TypeProvider typeProvider)
            : this()
        {
            if (@interface == null) throw new ArgumentNullException("interface");
            if (attribute == null) throw new ArgumentNullException("attribute");
            if (typeProvider == null) throw new ArgumentNullException("typeProvider");

            int priority = 0;

            object value = attribute.NamedParameter("Priority").ConstantValue.Value;
            if (value != null)
                int.TryParse(value.ToString(), out priority);

            value = attribute.NamedParameter("ViewTypeName").ConstantValue.Value;
            if (value != null)
            {
                string uiViewName = value.ToString();
                IDeclaredType declaredType = typeProvider.GetDeclaredType(uiViewName);
                if (!declaredType.IsObject())
                    UiViewType = declaredType;
            }

            var name = attribute.NamedParameter("Name").ConstantValue.Value as string;
            if (string.IsNullOrWhiteSpace(name))
                name = @interface.GetMemberName();

            ViewType = TypeFactory.CreateType(@interface);
            Name = name;
            Priority = priority;
        }

        public ViewMetaModel([NotNull] IDeclaredType viewType, IDeclaredType uiViewType, [NotNull] string name,
            int priority)
            : this()
        {
            if (viewType == null) throw new ArgumentNullException("viewType");
            if (name == null) throw new ArgumentNullException("name");
            ViewType = viewType;
            UiViewType = uiViewType;
            Name = name;
            Priority = priority;
        }

        #endregion

        #region Properties

        public IDeclaredType ViewType { get; private set; }

        public IDeclaredType UiViewType { get; private set; }

        public string Name { get; private set; }

        public int Priority { get; private set; }

        #endregion
    }
}